/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package helikopter_logger;

import java.net.*;
import java.text.Format;
import java.text.SimpleDateFormat;
/**
 *
 * @author Törcsi
 */
public class UDP {
    public static String toHexString(byte[] ba) {
        StringBuilder str = new StringBuilder();
        for(int i = 0; i < ba.length; i++)
            str.append(String.format("%x", ba[i]));
        return str.toString();
    }
    public static String toHex(byte[] ba)
    {
        String ret="";
        for(int i = 0; i < ba.length; i++)
        {
            String var=String.format("%x", ba[i]);
            if(var.length()==1)
               ret=ret+'0';
            ret=ret + var;
        }
        return ret;
    }

    public static void start(int iport) throws Exception
      {
         DatagramSocket serverSocket = new DatagramSocket(iport);
            byte[] receiveData = new byte[4];
            byte[] sendData = new byte[1024];
            while(true)
               {
                  DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
                  serverSocket.receive(receivePacket);
                  String sentence = new String( receivePacket.getData());
                  String sentence2 =  toHex(receivePacket.getData());
                  long time = System.currentTimeMillis();
                  java.util.Date date = new java.sql.Date(time);
                  SimpleDateFormat ft = new SimpleDateFormat ("yyyy.MM.dd 'at' hh:mm:ss");
                  System.out.println(ft.format(date) + " RECEIVED: " /*+ sentence + " "*/ + sentence2);
                  InetAddress IPAddress = receivePacket.getAddress();
                  int port = receivePacket.getPort();
                  String capitalizedSentence = sentence.toUpperCase();
                  sendData = capitalizedSentence.getBytes();
                  DatagramPacket sendPacket =
                  new DatagramPacket(sendData, sendData.length, IPAddress, port);
                  serverSocket.send(sendPacket);
               }
      }
}
